require('./class.js');

exports.DBObject = Class.extend({
    _data: {},
    _updates: {},

    /*
     * @brief 构造函数
     */
    init: function(id) {
        this._data._id = id;
    },

    /*
     * @brief 获得数据库句柄
     */
    getDB: function() {
        return null;
    },

    /*
     * @brief 获得类名
     */
    getClassName: function() {
        return "Class";
    },

    /*
     * @brief 重置数据
     */
    reset: function() {
    },


    getId: function() {
        return this._data._id;
    },

    get: function(key) {
        return this._data[key];
    },

    set: function(key, value) {
        this._data[key] = value;
    },

    create: function() {
        this.reset();
        this.getDB().insert(this._data, function(err, result){});
    },

    markDirty : function() {
        var data = this._data;
        var keyName = "";
        for (var i = 0; i < arguments.length; ++i) {
            var key = arguments[i];
            if (i != 0) {
                keyName += ".";
            }
            keyName += key.toString();

            if (!data.hasOwnProperty(key)) {
                ERROR(util.format('markDirty %s id:%s key:%s invalid', this.getClassName(), this.getId(), keyName));
                return;
            }
            data = data[key];
        }
        this._updates[keyName] = data;
    },

    save : function(force, callback) {
        if (!force && Object.keys(this._updates).length < 10 ) {
            callback && callback(true);
            return; 
        }

        var updates = this._updates;
        this._updates = {};
        this.getDB().update({_id :this.getId()}, {$set:updates}, function(err, result){
            if (err) {
                ERROR(util.format('SAVE %s id:%s err:%j updates:%j', this.getClassName(), this.getId(), updates, err));
                callback && callback(false);
            } else {
                ERROR(util.format('SAVE %s id:%s SUCCESS updates:%j', this.getClassName(), this.getId(), updates));
                callback && callback(true);
            }
        }.bind(this));
    },

    load : function(callback) {
        this.getDB().findOne({_id: this.getId()}, {}, function(err, doc){
            if (doc) {
                this._data = doc;
                callback && callback(true);
            } else {
                callback && callback(false);
            }
        }.bind(this));
    },
});
